﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PMS.Logic.PM
{
    public partial class BottleProductionAjax : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            String methodName = Request["method"];
            Type type = this.GetType();
            MethodInfo method = type.GetMethod(methodName);
            if (method == null) throw new Exception("method is null");
            try
            {
                method.Invoke(this, null);
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 获取气瓶配气信息
        /// </summary>
        public void GetBottleProductionList()
        {
            List<SearchCondition> listSearch = new List<SearchCondition>();
            if (Request.Form["searchData"] != null)
            {
                string searchData = Request.Form["searchData"];
                listSearch = ModelTools.GetSearchContions(searchData);
                if (listSearch.Where(s => s.Field == "startFillDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "startFillDate").FirstOrDefault().Field = "FillDate";
                }
                if (listSearch.Where(s => s.Field == "endFillDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "endFillDate").FirstOrDefault().Field = "FillDate";
                }

            }
            Expression<Func<View_PM_BottleProduction, bool>> exp = SearchExpression.FindByGroup<View_PM_BottleProduction>(listSearch);
            string OrderId = OperateContext.Sort == null ? "FillDate" : OperateContext.Sort;
            int count = 0;
            var list = DALSession.Current.View_PM_BottleProductionDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, exp, OrderId, false);
            count = DALSession.Current.View_PM_BottleProductionDAL.GetCount(exp);
            Response.Write(JsonHelper.toPageJson(list, count));
        }

        public void GetBottleProductionById()
        {
            string BarCode = Request.Form["BarCode"].ToString();
            View_PM_BottleProduction bottle = DALSession.Current.View_PM_BottleProductionDAL.GetListBy(b => b.SerialCode == BarCode).FirstOrDefault();
            Response.Write(JsonHelper.toJson(bottle));

        }

        /// <summary>
        /// 获取气瓶跟踪列表信息
        /// </summary>
        public void GetBottleTrackingList()
        {
            List<SearchCondition> listSearch = new List<SearchCondition>();
            if (Request.Form["searchData"] != null)
            {
                string searchData = Request.Form["searchData"];
                listSearch = ModelTools.GetSearchContions(searchData);
                if (listSearch.Where(s => s.Field == "startFillDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "startFillDate").FirstOrDefault().Field = "FillDate";
                }
                if (listSearch.Where(s => s.Field == "endFillDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "endFillDate").FirstOrDefault().Field = "FillDate";
                }

            }
            Expression<Func<View_PM_BottleTracking, bool>> exp = SearchExpression.FindByGroup<View_PM_BottleTracking>(listSearch);
            string OrderId = OperateContext.Sort == null ? "SerialCode" : OperateContext.Sort;
            int count = 0;
            var list = DALSession.Current.View_PM_BottleTrackingDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, exp, OrderId, false);
            count = DALSession.Current.View_PM_BottleTrackingDAL.GetCount(exp);
            Response.Write(JsonHelper.toPageJson(list, count));
        }

        /// <summary>
        /// 通过ID或者气瓶流水号获取气瓶追踪信息
        /// </summary>
        public void GetBottleTrackingByIDCode()
        {
            //通过ID查询
            if (Request.Form["ID"] != null && Request.Form["ID"] != "")
            {
                int id = Commons.String2Int32(Request.Form["ID"]);
                var per = DALSession.Current.View_PM_BottleTrackingDAL.GetListBy(p => p.ID == id).FirstOrDefault();
                Response.Write(JsonHelper.toJson(per));
                return;
            }
            //通过流水号查询
            if (Request.Form["BarCode"] != null && Request.Form["BarCode"] != "")
            {
                string Code = Request.Form["BarCode"];
                var per = DALSession.Current.View_PM_BottleTrackingDAL.GetListBy(p => p.SerialCode == Code).FirstOrDefault();
                if (per == null) per = new View_PM_BottleTracking();
                Response.Write(JsonHelper.toJson(per));
            }
            else
            {
                Response.Write(JsonHelper.toJson(new View_PM_BottleTracking()));
            }
        }


        private static readonly object objLock = new object();
        /// <summary>
        /// 前台绑定气瓶后添加配气信息
        /// </summary>
        public void AddBottleProductionInfo()
        {
            string data = Request.Form["data"];
            PM_BottleProduction per = new PM_BottleProduction();
            ModelTools.Form2EditModel(Request.Form, per);
            //插入气瓶信息
            BD_BottleInfo perBottle = new BD_BottleInfo()
            {
                BottleCode = Request.Form["BottleCode"],
                LastCheckDate = Request.Form["BottleCheckDate"],
                ProductionDate = Request.Form["BottleProdDate"],
                BottleVolume = Convert.ToDouble(Request.Form["BottleVolume"]),
                Note = Request.Form["BottleNote"]
            };
            if (Request.Form["MadeCodeid"] != null && Request.Form["MadeCodeid"] != "")
            {
                perBottle.BottleSupplierID = Convert.ToInt32(Request.Form["MadeCodeid"]);
            }
            int bottleId = Commons.String2Int32(DALSession.Current.BD_BottleInfoDAL.AddModelReturnId(perBottle, "ID"));
            per.BottleID = bottleId;

            string isPureGas = Request.Form["IsPureGas"];

            per.FillDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //添加默认状态为配气进行中，纯气默认为配气完成
            per.State = isPureGas == "1" ? "1" : "0";
            //打印状态默认未打印
            per.PrintState = "0";
            if (isPureGas == "1")
            {
                per.CompletedDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            }
            //添加默认分析状态为未分析
            per.AnalyseRes = "2";
            //生成流水号 yyMMdd0002
            //lock保证并发时不会生成重复流水号
            string newId = "";
            lock (objLock)
            {

                string time = DateTime.Now.ToString("yyMMdd");
                var con = DALSession.Current.PM_BottleProductionDAL.GetListBy(c => c.SerialCode.Substring(0, 6) == time, p => p.SerialCode, false).FirstOrDefault();
                if (con == null)
                {
                    newId = time + "0001";
                }
                else
                {
                    newId = time + (Commons.String2Int32(con.SerialCode.Substring(6, 4)) + 1).ToString().PadLeft(4, '0');
                }
                per.SerialCode = newId;
            }

            //查出生产订单
            var list = DALSession.Current.PM_ProductOrderDAL.GetListBy(c => c.ID == per.ProductOrderID).FirstOrDefault();
            //带出生产订单相关信息
            per.ProductOrderCode = list.Code;
            per.IsUrgent = list.IsUrgent;
            per.OrderDate = list.OrderDate;
            per.ReleaseDate = list.ReleaseDate;
            per.QuotationID = list.QuotationID;
            per.QuotationCode = list.QuotationCode;
            per.ContractID = list.ContractID;
            per.ContractCode = list.ContractCode;
            per.CustomerID = list.CustomerID;
            per.SupplierID = list.SupplierID;
            per.BudgetPressure = (decimal)10;
            per.PrintColumn = 1;
            per.PrintChiOrEng = "0";
            per.PrintIsAir = "0";
            per.PrintDeadline = "12";

            //per.ReceiveAddress = list.ReceiveAddress;
            //per.InvoiceAddress = list.InvoiceAddress;

            if (per.GBID != 0)
            {
                var gb = DALSession.Current.BD_GBInfoDAL.GetListBy(g => g.ID == per.GBID).FirstOrDefault();
                if (gb != null)
                {
                    per.kValue = gb.kValue;
                }
                else
                {
                    per.kValue = 2;
                }

            }
            else
            {
                per.kValue = 2;
            }

            var detailList = DALSession.Current.View_CM_QuotationDetailDetailDAL.GetListBy(c => c.QuotationDetailID == per.QuotationDetailID).OrderBy(c => c.IsBottomGas).ToList();
            var bottleGas = detailList.Where(c => c.IsBottomGas == "1").FirstOrDefault();
            if (bottleGas != null)
            {
                per.BottomGasID = bottleGas.GasID;
            }
            int ProId = Commons.String2Int32(DALSession.Current.PM_BottleProductionDAL.AddModelReturnId(per, "ID"));
            //插入配气师
            var PersonIDs = JsonConvert.DeserializeObject<List<int>>(Request.Form["PersonIDs"]);
            PersonIDs.ForEach(p =>
            {
                var newPerson = new PM_BottleProductionPerson()
                {
                    BottleProductionID = ProId,
                    UserID = p
                };
                DALSession.Current.PM_BottleProductionPersonDAL.Add(newPerson);
            });
            DALSession.Current.PM_BottleProductionPersonDAL.SaveChanges();
            var lastMain = DALSession.Current.PM_BottleProductionDAL.GetListBy(c => c.QuotationDetailID == per.QuotationDetailID && c.ID != ProId).OrderByDescending(c => c.ID).FirstOrDefault();
            List<PM_BottleProductionDetail> lastDetailList = new List<PM_BottleProductionDetail>();
            if (lastMain != null)
            {
                lastDetailList = DALSession.Current.PM_BottleProductionDetailDAL.GetListBy(b => b.MainId == lastMain.ID).ToList();
            }
            var gasList = DALSession.Current.View_BD_GasInfoDAL.GetListBy(g => 1 == 1).ToList();


            decimal gasConcentration = 0;
            int j = 1;
            foreach (var detail in detailList)
            {
                PM_BottleProductionDetail bottle = new PM_BottleProductionDetail();
                bottle.MainId = ProId;
                bottle.GasID = detail.GasID;
                // bottle.GasWeight = detail.GasWeight;
                var unitName = "ppm";
                switch (detail.CusUnit)
                {
                    case "1":
                        unitName = "%";
                        break;
                    case "2":
                        unitName = "mg/m3";
                        bottle.PrintUnit = "1";
                        break;
                    case "3":
                        unitName = "lel";
                        break;
                    default:
                        unitName = "ppm";
                        break;
                }
                bottle.CusConcUnit = detail.CusConcen.ToString().TrimEnd('0').TrimEnd('.') + unitName;
                bottle.BudgetConcentration = detail.Concentration / 10000;
                bottle.ActualConcentration = 0;
                bottle.TotalWeight = 0;
                bottle.SampleVolume = 0;
                bottle.Concentration = 0;
                bottle.SingleWeight = 0;
                bottle.BudgetWeight = 0;
                bottle.OneConcentration = 0;
                bottle.OneBottleCode = "";
                bottle.BudgetPressure = 0;
                bottle.IsBottom = "0";
                bottle.QuotationNote = detail.Note;
                //如果是纯气则默认配气完成
                bottle.IsComplete = isPureGas == "1" ? "1" : "0";
                //先给个初始较大的排序
                bottle.OperOrder = 99;
                bottle.GasWeight = (decimal)detail.GasWeight;
                bottle.CalculateGasWeight = (decimal)detail.GasWeight;
                bottle.IsBottom = detail.IsBottomGas;
                bottle.PrintDigitNum = 3;
                bottle.InputGroup = j;
                bottle.IsGroupMain = "0";
                bottle.EverageWeight = 0;
                j++;

                //如果是底气 默认分析方法为空
                if (bottle.IsBottom == "1")
                {
                    bottle.AnalyseMethod = "";
                    bottle.OneConcentration = 100;
                }

                if (lastDetailList.Count != 0)
                {
                    var once = lastDetailList.Where(l => l.GasID == detail.GasID).FirstOrDefault();
                    if (once != null)
                    {
                        bottle.OneConcentration = once.OneConcentration;
                        bottle.OneBottleCode = once.OneBottleCode;

                    }
                }
                if (detailList.Count > 1)
                {
                    if (detail.IsBottomGas == "0")
                    {
                        gasConcentration += detail.Concentration;
                    }
                    else
                    {
                        bottle.BudgetConcentration = (1000000 - gasConcentration) / 10000;
                    }
                }


                if (detail.IsPureGas == "1")
                {
                    bottle.Concentration = detail.Concentration / 10000;
                    bottle.AnalyseConcentration = detail.Concentration / 10000;
                }

                //获取分析方法 不是底气的气体才赋值，底气为空
                var basGas = gasList.Where(g => g.ID == detail.GasID && detail.IsBottomGas == "0").FirstOrDefault();
                if (basGas != null)
                {
                    bottle.AnalyseMethod = basGas.AnalyseMethod;
                }

                DALSession.Current.PM_BottleProductionDetailDAL.Add(bottle);

            }
            DALSession.Current.PM_BottleProductionDAL.SaveChanges();
            Message msg = new Message() { state = "success", msg = "保存成功", returnValue = newId };
            Response.Write(JsonHelper.toJson(msg));
        }

        public void GetNotInflatedList()
        {

            string BarCode = Request.Form["BarCode"].ToString();
            var production = DALSession.Current.PM_BottleProductionDAL.GetListBy(b => b.SerialCode == BarCode).FirstOrDefault();
            List<View_PM_BottleProductionDetail> list = new List<View_PM_BottleProductionDetail>();
            if (production != null)
            {
                list = DALSession.Current.View_PM_BottleProductionDetailDAL.GetListBy(c => c.MainId == production.ID).OrderBy(o => o.OperOrder).ThenBy(o => o.InputGroup).ThenByDescending(o => o.IsGroupMain).ToList();
            }

            Response.Write(JsonHelper.toJson(list));

        }

        public void JumpCompute()
        {
            PM_BottleProduction production = new PM_BottleProduction();
            production.ID = Commons.String2Int32(Request.Form["MainId"]);
            production.State = "1";
            DALSession.Current.PM_BottleProductionDAL.ModifyBy(production, p => p.ID == production.ID, "State");
            DALSession.Current.PM_BottleProductionDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "完成充气"));

        }


        /// <summary>
        /// 修改气瓶绑定信息
        /// </summary>
        public void EditBottleProduction()
        {
            int ID = Commons.String2Int32(Request.Form["ID"]);
            PM_BottleProduction perNew = DALSession.Current.PM_BottleProductionDAL.GetListBy(d => d.ID == ID).FirstOrDefault();
            ModelTools.Form2EditModel(Request.Form, perNew);
            DALSession.Current.PM_BottleProductionDAL.ModifyAllModel(perNew);
            DALSession.Current.PM_BottleProductionDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "保存成功"));
        }

        /// <summary>
        /// 删除气瓶生产信息
        /// </summary>
        public void DelBottleProduction()
        {
            if (Request.Form["ID"] == null)
            {
                Response.Write(JsonHelper.toDefaultMsg(false, "删除失败"));
                return;
            }
            int Id = Convert.ToInt32(Request.Form["ID"].ToString());
            var per = DALSession.Current.PM_BottleProductionDAL.GetListBy(p => p.ID == Id).FirstOrDefault();
            var prodID = per.ProductOrderID;
            if (per.State == "3")
            {
                Response.Write(JsonHelper.toDefaultMsg(false, "当前气瓶已入库完成，无法删除！"));
                return;
            }
            else if (per.State == "4")
            {
                Response.Write(JsonHelper.toDefaultMsg(false, "当前气瓶已发货完成，无法删除！"));
                return;
            }
            DALSession.Current.PM_BottleProductionDAL.DelBy(p => p.ID == Id);
            DALSession.Current.PM_BottleProductionDAL.SaveChanges();
            //级联删除，删除掉该气瓶下对应的组分浓度计算记录
            DALSession.Current.PM_BottleProductionDetailDAL.DelBy(p => p.MainId == Id);
            DALSession.Current.PM_BottleProductionDetailDAL.SaveChanges();
            //删除掉该气瓶下对应的配气师记录
            DALSession.Current.PM_BottleProductionPersonDAL.DelBy(p => p.BottleProductionID == Id);
            DALSession.Current.PM_BottleProductionPersonDAL.SaveChanges();
            //更新生产订单是否完成状态
            ProductOrderAjax.SetProductOrderIsComplete((int)prodID);
            Response.Write(JsonHelper.toDefaultMsg(true, "删除成功"));
        }

        #region 配气相关操作

        /// <summary>
        /// 设置配气过程的底气
        /// </summary>
        public void SetBottleGas()
        {
            if (Request.Form["GasId"] != null)
            {
                int GasId = Commons.String2Int32(Request.Form["GasId"]);
                var Detail = DALSession.Current.View_PM_BottleProductionDetailDAL.GetListBy(b => b.ID == GasId).FirstOrDefault();
                //var otherDetailList = DALSession.Current.View_PM_BottleProductionDetailDAL.GetListBy(b => b.MainId == Detail.MainId && b.ID != GasId).ToList();

                int beginCount = DALSession.Current.PM_BottleProductionDetailDAL.GetCount(b => b.MainId == Detail.MainId && b.IsComplete == "1");
                if (beginCount == 0)
                {
                    PM_BottleProduction main = new PM_BottleProduction() { BottomGasID = GasId };
                    var bottomDetail = new PM_BottleProductionDetail() { IsBottom = "1" };
                    var NotBottleDetail = new PM_BottleProductionDetail() { IsBottom = "0" };

                    DALSession.Current.PM_BottleProductionDAL.ModifyBy(main, b => b.ID == Detail.MainId, "BottomGasID");
                    DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(bottomDetail, b => b.ID == GasId, "IsBottom");
                    DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(NotBottleDetail, b => b.MainId == Detail.MainId && b.ID != GasId, "IsBottom");
                    DALSession.Current.PM_BottleProductionDAL.SaveChanges();

                    Response.Write(JsonHelper.toDefaultMsg(true, "设置成功"));
                    return;
                }
                else
                {
                    Response.Write(JsonHelper.toDefaultMsg(false, "开始充气后，无法设置底气！"));
                    return;
                }
            }
            else
            {
                Response.Write(JsonHelper.toDefaultMsg(false, "设置失败"));
                return;
            }

        }

        //合并气体
        public void MergeGas()
        {
            PM_BottleProduction production = new PM_BottleProduction();
            ModelTools.Form2EditModel(Request.Form, production);
            production.ID = Commons.String2Int32(Request.Form["MainId"]);
            string StrCurrentRows = Request.Form["row"];
            List<PM_BottleProductionDetail> currentRows = JsonConvert.DeserializeObject<List<PM_BottleProductionDetail>>(StrCurrentRows);
            var inPutGroup = DALSession.Current.PM_BottleProductionDetailDAL.GetListBy(b => b.MainId == production.ID).OrderByDescending(o => o.InputGroup).FirstOrDefault().InputGroup;
            int newGroupId = (int)inPutGroup + 1;
            foreach (var rows in currentRows)
            {
                rows.InputGroup = newGroupId;

                DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(rows, c => c.ID == rows.ID, "InputGroup");
            }
            DALSession.Current.PM_BottleProductionDetailDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "合并完成！"));
            return;
        }


        public void CompleteMutliGas()
        {
            PM_BottleProduction production = new PM_BottleProduction();
            ModelTools.Form2EditModel(Request.Form, production);
            production.ID = Commons.String2Int32(Request.Form["MainId"]);
            var detailList = DALSession.Current.PM_BottleProductionDetailDAL.GetListBy(b => b.MainId == production.ID).ToList();
            int count = detailList.Count(d => d.Concentration == null || d.Concentration == 0);
            if (count == 0)
            {

                production.State = "1";
                production.CompletedDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                DALSession.Current.PM_BottleProductionDAL.ModifyBy(production, b => b.ID == production.ID, "State", "CompletedDate");
                DALSession.Current.PM_BottleProductionDetailDAL.SaveChanges();
                Response.Write(JsonHelper.toDefaultMsg(true, "配气完成！"));
                return;
            }
            else
            {
                Response.Write(JsonHelper.toDefaultMsg(false, "请保证浓度不为空！"));
                return;
            }
        }


        public void CompleteGas()
        {
            int ID = Commons.String2Int32(Request.Form["MainId"]);
            string detailString = Request.Form["Detail"];
            string currentRowArray = Request.Form["currentRowArray"];
            PM_BottleProduction production = DALSession.Current.PM_BottleProductionDAL.GetListBy(p => p.ID == ID).FirstOrDefault();

            ModelTools.Form2EditModel(Request.Form, production);
            production.ID = Commons.String2Int32(Request.Form["MainId"]);
            //PM_BottleProductionDetail currentDetail = new PM_BottleProductionDetail();
            //ModelTools.Form2EditModel(Request.Form, currentDetail);
            PM_BottleProductionDetail currentDetail = JsonConvert.DeserializeObject<List<PM_BottleProductionDetail>>(currentRowArray).FirstOrDefault();
            List<PM_BottleProductionDetail> detailList = JsonConvert.DeserializeObject<List<PM_BottleProductionDetail>>(detailString).OrderBy(b => b.OperOrder).ToList();
            int CompleteNum = detailList.Count(d => d.IsComplete == "1");
            PM_BottleProductionDetail bottleGas = detailList.Where(d => d.IsBottom == "1").FirstOrDefault();

            if (bottleGas == null && detailList.Count == 1)
            {
                //样气质量
                currentDetail.SingleWeight = currentDetail.TotalWeight - production.EmptyBottleWeight;
                currentDetail.IsComplete = "1";
                DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(currentDetail, c => c.ID == currentDetail.ID, "TotalWeight", "SingleWeight", "BudgetWeight", "SampleVolume", "IsComplete", "MidValueL", "OperOrder", "OneBottleCode");
                production.State = "1";
                production.CompletedDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                DALSession.Current.PM_BottleProductionDAL.ModifyBy(production, b => b.ID == production.ID, "TotalNum", "State", "CompletedDate");
                DALSession.Current.PM_BottleProductionDetailDAL.SaveChanges();
                Response.Write(JsonHelper.toDefaultMsg(true, "计算完成"));
                return;
            }
            else if (bottleGas == null && detailList.Count > 1)
            {
                Response.Write(JsonHelper.toDefaultMsg(true, "请选择底气，并保存！"));
                return;
            }
            else
            {
                if (CompleteNum == 0)
                {
                    currentDetail.OperOrder = 1;

                    if (Commons.String2Decimal(currentDetail.SingleWeight) == 0)
                    {
                        //样气质量
                        currentDetail.SingleWeight = currentDetail.TotalWeight - production.EmptyBottleWeight;
                    }
                    else
                    {
                        currentDetail.SingleWeight = Commons.String2Decimal(currentDetail.SingleWeight);
                        currentDetail.TotalWeight = production.EmptyBottleWeight + currentDetail.SingleWeight;
                    }




                    //中间值 L5
                    currentDetail.MidValueL = 1 / ((1 / (decimal)currentDetail.OneConcentration * 100 - 1) * (decimal)bottleGas.CalculateGasWeight / (decimal)currentDetail.CalculateGasWeight + 1);
                    currentDetail.BudgetWeight = (decimal)currentDetail.SingleWeight * currentDetail.MidValueL;
                    //中间值 K3
                    decimal midValue2 = (decimal)(currentDetail.BudgetWeight / (decimal)currentDetail.CalculateGasWeight / currentDetail.BudgetConcentration * 100);
                    production.MidK3 = midValue2;
                    DALSession.Current.PM_BottleProductionDAL.ModifyBy(production, c => c.ID == production.ID, "MidK3");
                    //中间值M5
                    decimal midValue3 = (decimal)((decimal)currentDetail.CalculateGasWeight * currentDetail.OneConcentration / 100 + (decimal)bottleGas.CalculateGasWeight * (1 - currentDetail.OneConcentration / 100));
                    currentDetail.SampleVolume = Math.Round((decimal)(currentDetail.SingleWeight / midValue3), 6, MidpointRounding.AwayFromZero);
                    currentDetail.IsComplete = "1";
                    DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(currentDetail, c => c.ID == currentDetail.ID, "TotalWeight", "SingleWeight", "BudgetWeight", "SampleVolume", "IsComplete", "MidValueL", "OperOrder", "OneBottleCode");

                    foreach (var detail in detailList)
                    {
                        if (detail.ID != currentDetail.ID)
                        {
                            if (detail.OneConcentration != null && detail.OneConcentration != 0)
                            {
                                //中间值L
                                detail.MidValueL = 1 / (decimal)((1 / detail.OneConcentration * 100 - 1) * bottleGas.CalculateGasWeight / detail.CalculateGasWeight + 1);
                                // 预算克数
                                detail.BudgetWeight = midValue2 * detail.CalculateGasWeight * detail.BudgetConcentration / 100 / detail.MidValueL;
                                //预算压力
                                detail.BudgetPressure = detail.BudgetConcentration / 100 * production.BudgetPressure / detail.OneConcentration * 100;

                                //先不计算底气的预算克数
                                if (detail.IsBottom == "1")
                                {
                                    var udateDetailList = DALSession.Current.PM_BottleProductionDetailDAL.GetListBy(d => d.MainId == currentDetail.MainId).ToList();
                                    detail.MidValueL = 1 / (decimal)((1 / detail.OneConcentration * 100 - 1) * detail.CalculateGasWeight / detail.CalculateGasWeight + 1);
                                    decimal error = (decimal)udateDetailList.Where(d => d.IsBottom == "0" && d.IsComplete == "1").Sum(d => d.SingleWeight - d.SingleWeight * d.MidValueL);
                                    detail.BudgetWeight = (decimal)(production.MidK3 * detail.CalculateGasWeight * detail.BudgetConcentration / 100 / detail.MidValueL) - error;
                                    //计算底气的相关信息
                                    DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(detail, b => b.ID == detail.ID, "MidValueL", "BudgetWeight");
                                }
                                ////中间值M
                                //decimal midM = (decimal)((decimal)detail.GasWeight * detail.OneConcentration / 100 + (decimal)bottleGas.GasWeight * (1 - currentDetail.OneConcentration / 100));
                                DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(detail, d => d.ID == detail.ID, "BudgetWeight", "BudgetPressure", "MidValueL");
                            }
                        }
                    }
                    production.BudgetTotalNum = currentDetail.BudgetWeight / currentDetail.CalculateGasWeight / currentDetail.BudgetConcentration * 100;
                    DALSession.Current.PM_BottleProductionDAL.ModifyBy(production, d => d.ID == production.ID, "BudgetTotalNum");

                    DALSession.Current.PM_BottleProductionDetailDAL.SaveChanges();
                    Response.Write(JsonHelper.toJson(new Message() { msg = "计算完成", state = "success", returnValue = production.MidK3.ToString() }));
                    return;
                }
                else if (CompleteNum == detailList.Count - 1)
                {
                    var LastDetail = detailList.Where(d => d.IsComplete == "1" && d.ID != currentDetail.ID).OrderByDescending(d => d.OperOrder).FirstOrDefault();

                    if (Commons.String2Decimal(currentDetail.SingleWeight) == 0)
                    {
                        currentDetail.SingleWeight = currentDetail.TotalWeight - LastDetail.TotalWeight;
                    }
                    else
                    {
                        currentDetail.SingleWeight = Commons.String2Decimal(currentDetail.SingleWeight);
                        currentDetail.TotalWeight = LastDetail.TotalWeight + currentDetail.SingleWeight;
                    }
                    //中间值M
                    decimal midM = (decimal)((decimal)currentDetail.CalculateGasWeight * currentDetail.OneConcentration / 100 + (decimal)bottleGas.CalculateGasWeight * (1 - currentDetail.OneConcentration / 100));

                    currentDetail.SampleVolume = Math.Round((decimal)(currentDetail.SingleWeight / midM), 6, MidpointRounding.AwayFromZero);
                    currentDetail.IsComplete = "1";

                    var OtherCompleteDetailList = detailList.Where(d => d.IsComplete == "1").ToList();

                    production.TotalNum = OtherCompleteDetailList.Sum(d => d.SampleVolume) + currentDetail.SampleVolume;
                    production.State = "1";
                    production.CompletedDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    DALSession.Current.PM_BottleProductionDAL.ModifyBy(production, b => b.ID == production.ID, "TotalNum", "State", "CompletedDate");
                    DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(currentDetail, c => c.ID == currentDetail.ID, "SingleWeight", "SampleVolume", "IsComplete", "TotalWeight");
                    DALSession.Current.PM_BottleProductionDetailDAL.SaveChanges();
                    var saveList = DALSession.Current.PM_BottleProductionDetailDAL.GetListBy(c => c.MainId == production.ID).OrderBy(c => c.IsBottom).ThenBy(c => c.OperOrder).ToList();
                    var notSaveBottleList = saveList.Where(c => c.IsBottom == "0").ToList();
                    foreach (var notSaveBottle in notSaveBottleList)
                    {
                        notSaveBottle.Concentration = notSaveBottle.SampleVolume / production.TotalNum * notSaveBottle.OneConcentration;
                        DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(notSaveBottle, d => d.ID == notSaveBottle.ID, "Concentration");
                    }
                    var saveBottle = saveList.Where(c => c.IsBottom == "1").FirstOrDefault();
                    if (saveBottle != null)
                    {
                        saveBottle.Concentration = 100 - notSaveBottleList.Sum(c => c.Concentration);
                        DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(saveBottle, d => d.ID == saveBottle.ID, "Concentration");
                    }


                    //foreach (var detail in OtherCompleteDetailList)
                    //{

                    //    DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(detail, d => d.ID == detail.ID, "Concentration");
                    //}

                    //currentDetail.Concentration = 100 - OtherCompleteDetailList.Sum(c => c.Concentration);


                    DALSession.Current.PM_BottleProductionDetailDAL.SaveChanges();
                    Response.Write(JsonHelper.toJson(new { state = "success", msg = "操作完成", TotalNum = production.TotalNum.ToString() }));
                    return;


                }
                else
                {
                    var LastDetail = detailList.Where(d => d.IsComplete == "1" && d.ID != currentDetail.ID).OrderByDescending(d => d.OperOrder).FirstOrDefault();
                    if (Commons.String2Decimal(currentDetail.SingleWeight) == 0)
                    {
                        currentDetail.SingleWeight = currentDetail.TotalWeight - LastDetail.TotalWeight;
                    }
                    else
                    {
                        currentDetail.SingleWeight = Commons.String2Decimal(currentDetail.SingleWeight);
                        currentDetail.TotalWeight = LastDetail.TotalWeight + currentDetail.SingleWeight;
                    }
                    currentDetail.IsComplete = "1";
                    currentDetail.OperOrder = LastDetail.OperOrder + 1;
                    //中间值M
                    decimal midM = (decimal)((decimal)currentDetail.CalculateGasWeight * currentDetail.OneConcentration / 100 + (decimal)bottleGas.CalculateGasWeight * (1 - currentDetail.OneConcentration / 100));
                    currentDetail.SampleVolume = Math.Round((decimal)(currentDetail.SingleWeight / midM), 6, MidpointRounding.AwayFromZero);
                    DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(currentDetail, c => c.ID == currentDetail.ID, "SingleWeight", "SampleVolume", "IsComplete", "TotalWeight", "OperOrder", "OneBottleCode");
                    DALSession.Current.PM_BottleProductionDetailDAL.SaveChanges();
                    //if (currentDetail.OperOrder == detailList.Count - 1)
                    //{

                    if (bottleGas.OneConcentration != 0 && bottleGas.OneConcentration != null && bottleGas.IsComplete == "0" && currentDetail.IsBottom == "1")
                    {
                        bottleGas.MidValueL = 1 / (decimal)((1 / bottleGas.OneConcentration * 100 - 1) * bottleGas.CalculateGasWeight / bottleGas.CalculateGasWeight + 1);

                        var udateDetailList = DALSession.Current.PM_BottleProductionDetailDAL.GetListBy(d => d.MainId == currentDetail.MainId).ToList();
                        decimal error = (decimal)udateDetailList.Where(d => d.OperOrder <= currentDetail.OperOrder).Sum(d => d.SingleWeight - d.SingleWeight * d.MidValueL);

                        bottleGas.BudgetWeight = (decimal)(Commons.String2Decimal(production.MidK3) * bottleGas.CalculateGasWeight * bottleGas.BudgetConcentration / 100 / bottleGas.MidValueL) - error;
                        //计算底气的相关信息
                        DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(bottleGas, b => b.ID == bottleGas.ID, "MidValueL", "BudgetWeight");
                    }

                    //}
                    DALSession.Current.PM_BottleProductionDetailDAL.SaveChanges();
                    Response.Write(JsonHelper.toDefaultMsg(true, "计算完成"));
                    return;
                }
            }
        }

        public void ReInputGas()
        {

            PM_BottleProductionDetail detail = new PM_BottleProductionDetail();
            ModelTools.Form2EditModel(Request.Form, detail);

            var viewBottle = DALSession.Current.View_PM_BottleAnalyseListDAL.GetListBy(b => b.ID == detail.MainId).FirstOrDefault();
            if (viewBottle != null)
            {
                if (viewBottle.State == "2" && viewBottle.AnalyseRes == "0")
                {
                    Response.Write(JsonHelper.toDefaultMsg(true, "该气体已配齐完成并分析合格，无法重新配气！"));
                    return;
                }
                else
                {
                    //ID, MainId, GasID, Concentration, OneConcentration, BudgetConcentration, SingleWeight, TotalWeight, SampleVolume, BudgetWeight, BudgetPressure, ActualConcentration, OperOrder, IsBottom, IsComplete, AnalyseMethod, AnalyseConcentration, AnalyseFile, AnalyseNote, GasWeight, MidValueL
                    detail.Concentration = 0;
                    detail.SingleWeight = 0;
                    detail.TotalWeight = 0;
                    detail.SampleVolume = 0;
                    detail.IsComplete = "0";
                    //detail.OneConcentration = 0;
                    //detail.BudgetPressure = 0;
                    detail.EverageWeight = 0;
                    detail.BudgetWeight = 0;
                    int oldOperOrder = (int)detail.OperOrder;
                    detail.OperOrder = 99;
                    // detail.MidValueL = 0;

                    DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(detail, d => d.OperOrder >= oldOperOrder && d.MainId == detail.MainId, "Concentration", "SingleWeight", "TotalWeight", "SampleVolume", "BudgetWeight", "IsComplete", "OperOrder", "EverageWeight");
                    PM_BottleProduction product = new PM_BottleProduction();
                    product.State = "0";
                    DALSession.Current.PM_BottleProductionDAL.ModifyBy(product, d => d.ID == detail.MainId, "State");
                    DALSession.Current.PM_BottleProductionDAL.SaveChanges();
                    Response.Write(JsonHelper.toDefaultMsg(true, "重置成功！"));
                    return;
                }
            }
            else
            {
                Response.Write(JsonHelper.toDefaultMsg(true, "未找到数据！"));
                return;
            }




        }

        /// <summary>
        /// 保存配气数据
        /// </summary>
        public void SaveGeneralAssingGas()
        {
            //  string data = Request.Form["Total"];
            int ID = Commons.String2Int32(Request.Form["MainId"]);

            PM_BottleProduction per = DALSession.Current.PM_BottleProductionDAL.GetListBy(p => p.ID == ID).FirstOrDefault();
            ModelTools.Form2EditModel(Request.Form, per);
            string detailString = Request.Form["Detail"];
            List<PM_BottleProductionDetail> detailList = JsonConvert.DeserializeObject<List<PM_BottleProductionDetail>>(detailString);
            PM_BottleProductionDetail bottleGas = detailList.Where(d => d.IsBottom == "1").FirstOrDefault();
            DALSession.Current.PM_BottleProductionDAL.ModifyBy(per, b => b.ID == per.ID, "EmptyBottleWeight", "BudgetPressure", "TotalNum");
            DALSession.Current.PM_BottleProductionDAL.SaveChanges();
            var newPer = DALSession.Current.PM_BottleProductionDAL.GetListBy(b => b.ID == per.ID).FirstOrDefault();

            int completeCount = detailList.Count(d => d.IsComplete == "1");

            foreach (var detail in detailList)
            {
                detail.OneConcentration = Commons.String2Decimal(detail.OneConcentration);
                detail.CalculateGasWeight = Commons.String2Decimal(detail.CalculateGasWeight);
                if (detail.OneConcentration != 0 && detail.IsComplete == "0")
                {
                    if (detail.IsBottom == "0")
                    {
                        if (completeCount != 0)
                        {
                            //中间值L
                            detail.MidValueL = 1 / (decimal)((1 / detail.OneConcentration * 100 - 1) * bottleGas.CalculateGasWeight / detail.CalculateGasWeight + 1);
                            // 预算克数
                            detail.BudgetWeight = newPer.MidK3 * detail.CalculateGasWeight * detail.BudgetConcentration / 100 / detail.MidValueL;
                        }
                        //预算压力
                        detail.BudgetPressure = detail.BudgetConcentration / 100 * newPer.BudgetPressure / detail.OneConcentration * 100;
                    }
                    else if (detail.IsBottom == "1" && detail.IsComplete == "0")
                    {

                        detail.BudgetConcentration = 100 - detailList.Where(d => d.IsBottom == "0").Sum(d => d.BudgetConcentration);


                        //if (completeCount == detailList.Count - 1)
                        //{
                        //中间值L
                        detail.MidValueL = 1 / (decimal)((1 / detail.OneConcentration * 100 - 1) * bottleGas.CalculateGasWeight / detail.CalculateGasWeight + 1);
                        decimal error = (decimal)detailList.Where(d => d.IsBottom == "0").Sum(d => d.SingleWeight - d.SingleWeight * d.MidValueL);

                        detail.BudgetWeight = (decimal)(Commons.String2Decimal(newPer.MidK3) * detail.CalculateGasWeight * detail.BudgetConcentration / 100 / detail.MidValueL) - error;
                        //}
                        detail.BudgetPressure = detail.BudgetWeight * newPer.BudgetPressure / detail.OneConcentration / 1000;


                    }

                    detail.BudgetPressure = detail.BudgetConcentration * per.BudgetPressure / detail.OneConcentration;
                }
                DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(detail, d => d.ID == detail.ID, "Concentration", "TotalWeight", "SingleWeight", "SampleVolume", "BudgetWeight", "OneConcentration", "BudgetPressure", "MidValueL", "BudgetConcentration", "OneBottleCode", "CalculateGasWeight");
            }
            DALSession.Current.PM_ProductOrderDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "保存成功！"));
            return;
        }

        /// <summary>
        /// 跳过计算
        /// </summary>
        public void SkipCalc()
        {
            //直接配气完成
            int mainID = Commons.String2Int32(Request.Form["MainId"]);
            var per = DALSession.Current.PM_BottleProductionDAL.GetListBy(p => p.ID == mainID).FirstOrDefault();

            per.State = "1";
            per.PersonID = OperateContext.SessBasicInfo.UserInfo.Name;
            per.CompletedDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            DALSession.Current.PM_BottleProductionDAL.ModifyBy(per, b => b.ID == per.ID, "State", "CompletedDate", "PersonID");

            string detailString = Request.Form["Detail"];
            List<PM_BottleProductionDetail> detailList = JsonConvert.DeserializeObject<List<PM_BottleProductionDetail>>(detailString);
            detailList.ForEach(p =>
            {
                p.IsComplete = "1";
                p.PrintConcentration = "1";//默认打印分析浓度
                DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(p, b => b.ID == p.ID, "IsComplete", "PrintConcentration");
            });
            DALSession.Current.PM_BottleProductionDAL.SaveChanges();
            DALSession.Current.PM_BottleProductionDetailDAL.SaveChanges();
            //插入中间表 配气师
            //PM_BottleProductionPerson prodPerson = new PM_BottleProductionPerson()
            //{
            //    BottleProductionID = mainID,
            //    UserID = OperateContext.SessBasicInfo.UserInfo.Id
            //};
            //DALSession.Current.PM_BottleProductionPersonDAL.Add(prodPerson);
            //DALSession.Current.PM_BottleProductionPersonDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "保存成功！"));
        }

        /// <summary>
        /// 跳过计算与分析
        /// </summary>
        public void SkipCalcAna()
        {
            //直接配气完成、分析完成且分析结论为合格
            int mainID = Commons.String2Int32(Request.Form["MainId"]);
            var per = DALSession.Current.PM_BottleProductionDAL.GetListBy(p => p.ID == mainID).FirstOrDefault();

            per.State = "2";
            per.AnalyseRes = "0";
            per.AnalystID = OperateContext.SessBasicInfo.UserInfo.Id;
            per.PersonID = OperateContext.SessBasicInfo.UserInfo.Name;
            per.CompletedDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            per.AnalyseDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            DALSession.Current.PM_BottleProductionDAL.ModifyBy(per, b => b.ID == per.ID, "State", "AnalyseRes", "AnalystID", "PersonID", "CompletedDate", "AnalyseDate");


            string detailString = Request.Form["Detail"];
            List<PM_BottleProductionDetail> detailList = JsonConvert.DeserializeObject<List<PM_BottleProductionDetail>>(detailString);
            detailList.ForEach(p =>
            {
                p.IsComplete = "1";
                DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(p, b => b.ID == p.ID, "IsComplete");
            });
            DALSession.Current.PM_BottleProductionDAL.SaveChanges();
            DALSession.Current.PM_BottleProductionDetailDAL.SaveChanges();
            //更新订单完成状态
            ProductOrderAjax.SetProductOrderIsComplete((int)per.ProductOrderID);
            //插入中间表 配气师
            //PM_BottleProductionPerson prodPerson = new PM_BottleProductionPerson()
            //{
            //    BottleProductionID = mainID,
            //    UserID = OperateContext.SessBasicInfo.UserInfo.Id
            //};
            //DALSession.Current.PM_BottleProductionPersonDAL.Add(prodPerson);
            //DALSession.Current.PM_BottleProductionPersonDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "保存成功！"));
        }
        #endregion

        #region 超多元操作
        /// <summary>
        /// 保存配气数据
        /// </summary>
        public void SaveMultiAssingGas()
        {
            int ID = Commons.String2Int32(Request.Form["MainId"]);

            PM_BottleProduction per = DALSession.Current.PM_BottleProductionDAL.GetListBy(p => p.ID == ID).FirstOrDefault();
            ModelTools.Form2EditModel(Request.Form, per);

            string detailString = Request.Form["Detail"];
            List<PM_BottleProductionDetail> detailList = JsonConvert.DeserializeObject<List<PM_BottleProductionDetail>>(detailString);
            PM_BottleProductionDetail bottleGas = detailList.Where(d => d.IsBottom == "1").FirstOrDefault();
            DALSession.Current.PM_BottleProductionDAL.ModifyBy(per, b => b.ID == per.ID, "EmptyBottleWeight", "BudgetPressure", "TotalNum");
            DALSession.Current.PM_BottleProductionDAL.SaveChanges();
            var newPer = DALSession.Current.PM_BottleProductionDAL.GetListBy(b => b.ID == per.ID).FirstOrDefault();

            int completeCount = detailList.Count(d => d.IsComplete == "1");
            var groupList = detailList.OrderBy(o => o.IsBottom).ThenBy(o => o.OperOrder).GroupBy(d => d.InputGroup);
            foreach (var group in groupList)
            {
                foreach (var detail in group)
                {
                    detail.OneConcentration = Commons.String2Decimal(detail.OneConcentration);

                    if (detail.OneConcentration != 0 && detail.IsComplete == "0")
                    {
                        if (detail.IsBottom == "0")
                        {
                            if (completeCount != 0)
                            {
                                //计算质量分数
                                var O161 = group.Sum(c => c.OneConcentration / 100 * c.CalculateGasWeight);
                                var O162 = bottleGas.CalculateGasWeight * (1 - group.Sum(c => c.OneConcentration / 100));


                                detail.MidValueL = (detail.OneConcentration * detail.CalculateGasWeight) / 100 / (O161 + O162);
                                //预算量
                                detail.BudgetWeight = per.MidK3 * detail.CalculateGasWeight * detail.BudgetConcentration / detail.MidValueL / 100;
                            }
                            //预算压力
                            detail.BudgetPressure = detail.BudgetConcentration / 100 * newPer.BudgetPressure * 10 / detail.OneConcentration * 100;


                        }
                        else if (detail.IsBottom == "1" && detail.IsComplete == "0")
                        {

                            detail.BudgetConcentration = 100 - detailList.Where(d => d.IsBottom == "0").Sum(d => d.BudgetConcentration);

                            detail.EverageWeight = detailList.Where(d => d.ID != detail.ID).Sum(d => d.EverageWeight);
                            detail.BudgetWeight = Commons.String2Decimal(per.MidK3) * detail.BudgetConcentration / 100 * detail.CalculateGasWeight - detail.EverageWeight;

                            detail.BudgetPressure = 0;

                        }

                        detail.BudgetPressure = detail.BudgetConcentration * per.BudgetPressure * 10 / detail.OneConcentration;
                    }
                    DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(detail, d => d.ID == detail.ID, "Concentration", "TotalWeight", "SingleWeight", "SampleVolume", "BudgetWeight", "OneConcentration", "BudgetPressure", "MidValueL", "BudgetConcentration", "EverageWeight", "OneBottleCode", "CalculateGasWeight");
                }
            }

            DALSession.Current.PM_ProductOrderDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "保存成功！"));
            return;


        }


        public void ReMultiInputGas()
        {


            PM_BottleProductionDetail detail = new PM_BottleProductionDetail();
            ModelTools.Form2EditModel(Request.Form, detail);
            var viewBottle = DALSession.Current.View_PM_BottleAnalyseListDAL.GetListBy(b => b.ID == detail.MainId).FirstOrDefault();
            if (viewBottle != null)
            {
                if (viewBottle.State == "2" && viewBottle.AnalyseRes == "0")
                {
                    Response.Write(JsonHelper.toDefaultMsg(true, "该气体已配齐完成并分析合格，无法重新配气！"));
                    return;
                }
                else
                {
                    detail.Concentration = 0;
                    detail.SingleWeight = 0;
                    detail.TotalWeight = 0;
                    detail.SampleVolume = 0;
                    detail.IsComplete = "0";
                    //detail.OneConcentration = 0;
                    //  detail.BudgetPressure = 0;
                    detail.EverageWeight = 0;
                    detail.IsGroupMain = "0";
                    detail.BudgetWeight = 0;



                    int oldOperOrder = (int)detail.OperOrder;
                    detail.OperOrder = 99;
                    DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(detail, d => (d.OperOrder >= oldOperOrder || d.InputGroup == detail.InputGroup) && d.MainId == detail.MainId, "Concentration", "SingleWeight", "TotalWeight", "SampleVolume", "BudgetWeight", "IsComplete", "OperOrder", "EverageWeight", "IsGroupMain");
                    PM_BottleProduction product = new PM_BottleProduction();
                    product.State = "0";
                    DALSession.Current.PM_BottleProductionDAL.ModifyBy(product, d => d.ID == detail.MainId, "State");
                    DALSession.Current.PM_BottleProductionDAL.SaveChanges();
                    Response.Write(JsonHelper.toDefaultMsg(true, "重置成功！"));
                    return;
                }
            }
            else
            {
                Response.Write(JsonHelper.toDefaultMsg(true, "未找到数据！"));
                return;
            }
          
        }



        public void CompleteMultiGas()
        {
            string detailString = Request.Form["Detail"];
            string currentRowArray = Request.Form["currentRowArray"];
            int ID = Commons.String2Int32(Request.Form["MainId"]);
            PM_BottleProduction production = DALSession.Current.PM_BottleProductionDAL.GetListBy(p => p.ID == ID).FirstOrDefault();
            ModelTools.Form2EditModel(Request.Form, production);

            PM_BottleProductionDetail currentDetail = JsonConvert.DeserializeObject<List<PM_BottleProductionDetail>>(currentRowArray).FirstOrDefault();
            List<PM_BottleProductionDetail> detailList = JsonConvert.DeserializeObject<List<PM_BottleProductionDetail>>(detailString).OrderBy(b => b.OperOrder).ToList();
            int CompleteNum = detailList.Count(d => d.IsComplete == "1");
            PM_BottleProductionDetail bottleGas = detailList.Where(d => d.IsBottom == "1").FirstOrDefault();


            if (bottleGas == null && detailList.Count > 1)
            {
                Response.Write(JsonHelper.toDefaultMsg(true, "请选择底气，并保存！"));
                return;
            }
            else
            {
                if (CompleteNum == 0)
                {
                    currentDetail.OperOrder = 1;
                    currentDetail.IsGroupMain = "1";
                    currentDetail.IsComplete = "1";
                    //样气质量
                    if (Commons.String2Decimal(currentDetail.SingleWeight) == 0)
                    {
                        //样气质量
                        currentDetail.SingleWeight = currentDetail.TotalWeight - production.EmptyBottleWeight;
                    }
                    else
                    {
                        currentDetail.SingleWeight = Commons.String2Decimal(currentDetail.SingleWeight);
                        currentDetail.TotalWeight = production.EmptyBottleWeight + currentDetail.SingleWeight;
                    }
                    var groupList = detailList.Where(d => d.InputGroup == currentDetail.InputGroup).ToList();
                    //计算质量分数
                    var O161 = groupList.Sum(c => c.OneConcentration / 100 * c.CalculateGasWeight);
                    var O162 = bottleGas.CalculateGasWeight * (1 - groupList.Sum(c => c.OneConcentration / 100));


                    currentDetail.MidValueL = (currentDetail.OneConcentration * currentDetail.CalculateGasWeight) / 100 / (O161 + O162);

                    currentDetail.EverageWeight = currentDetail.SingleWeight * (1 - (groupList.Sum(c => c.CalculateGasWeight * c.OneConcentration)) / 100 / (O161 + O162));

                    //组分质量L  中间值 L5
                    currentDetail.SampleVolume = currentDetail.SingleWeight * currentDetail.MidValueL;

                    //组分摩尔量
                    var molVolumn = currentDetail.SampleVolume / currentDetail.CalculateGasWeight;
                    //预算量
                    currentDetail.BudgetWeight = molVolumn / currentDetail.BudgetConcentration * 100;
                    production.MidK3 = currentDetail.BudgetWeight;
                    DALSession.Current.PM_BottleProductionDAL.ModifyBy(production, c => c.ID == production.ID, "MidK3");


                    DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(currentDetail, c => c.ID == currentDetail.ID, "TotalWeight", "SingleWeight", "BudgetWeight", "SampleVolume", "IsComplete", "MidValueL", "OperOrder", "IsGroupMain", "EverageWeight");

                    foreach (var thisGroup in groupList)
                    {
                        if (thisGroup.ID != currentDetail.ID)
                        {
                            thisGroup.IsComplete = "1";
                            thisGroup.OperOrder = 1;
                            thisGroup.MidValueL = (thisGroup.OneConcentration * thisGroup.CalculateGasWeight) / 100 / (O161 + O162);
                            thisGroup.SampleVolume = currentDetail.SingleWeight * thisGroup.MidValueL;
                            DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(thisGroup, c => c.ID == thisGroup.ID, "MidValueL", "SampleVolume", "IsComplete", "OperOrder");
                        }
                    }

                    var otherGroupList = detailList.Where(d => d.InputGroup != currentDetail.InputGroup).OrderBy(o => o.IsBottom).ThenBy(o => o.OperOrder).GroupBy(d => d.InputGroup);
                    foreach (var otherGroup in otherGroupList)
                    {
                        foreach (var otherDetail in otherGroup)
                        {
                            if (otherDetail.OneConcentration != null && otherDetail.OneConcentration != 0)
                            {
                                //计算质量分数
                                otherDetail.MidValueL = (otherDetail.OneConcentration * otherDetail.CalculateGasWeight) / 100 / (otherGroup.Sum(c => c.OneConcentration / 100 * c.CalculateGasWeight) + bottleGas.CalculateGasWeight * (1 - otherGroup.Sum(c => c.OneConcentration / 100)));
                                //预算量
                                otherDetail.BudgetWeight = Commons.String2Decimal(production.MidK3) * otherDetail.CalculateGasWeight * otherDetail.BudgetConcentration / otherDetail.MidValueL / 100;

                                //先不计算底气的预算克数
                                if (otherDetail.IsBottom == "1")
                                {
                                    if (otherDetail.OneConcentration != 0 && otherDetail.OneConcentration != null)
                                    {
                                        //otherDetail.EverageWeight = detailList.Sum(d => d.EverageWeight);
                                        otherDetail.EverageWeight = currentDetail.EverageWeight;

                                        otherDetail.BudgetWeight = production.MidK3 * bottleGas.BudgetConcentration / 100 * bottleGas.CalculateGasWeight - otherDetail.EverageWeight;
                                        //计算底气的相关信息
                                        DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(otherDetail, b => b.ID == otherDetail.ID, "BudgetWeight", "EverageWeight");
                                    }
                                }

                                DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(otherDetail, d => d.ID == otherDetail.ID, "BudgetWeight", "BudgetPressure", "MidValueL");
                            }
                        }
                    }

                    production.BudgetTotalNum = molVolumn / currentDetail.BudgetConcentration * 100;
                    DALSession.Current.PM_BottleProductionDAL.ModifyBy(production, d => d.ID == production.ID, "BudgetTotalNum");
                    DALSession.Current.PM_BottleProductionDetailDAL.SaveChanges();
                    Response.Write(JsonHelper.toDefaultMsg(true, "计算完成"));
                    return;
                }
                else
                {
                    var LastDetail = detailList.Where(d => d.IsComplete == "1" && d.IsGroupMain == "1" && d.ID != currentDetail.ID).OrderByDescending(d => d.OperOrder).FirstOrDefault();

                    if (Commons.String2Decimal(currentDetail.SingleWeight) == 0)
                    {
                        currentDetail.SingleWeight = currentDetail.TotalWeight - LastDetail.TotalWeight;
                    }
                    else
                    {
                        currentDetail.SingleWeight = Commons.String2Decimal(currentDetail.SingleWeight);
                        currentDetail.TotalWeight = LastDetail.TotalWeight + currentDetail.SingleWeight;
                    }
                    currentDetail.IsComplete = "1";
                    currentDetail.IsGroupMain = "1";
                    currentDetail.OperOrder = LastDetail.OperOrder + 1;
                    if (currentDetail.IsBottom == "0")
                    {
                        var groupList = detailList.Where(d => d.InputGroup == currentDetail.InputGroup).ToList();
                        currentDetail.MidValueL = (currentDetail.OneConcentration * currentDetail.CalculateGasWeight) / 100 / (groupList.Sum(c => c.OneConcentration / 100 * c.CalculateGasWeight) + bottleGas.CalculateGasWeight * (1 - groupList.Sum(c => c.OneConcentration / 100)));
                        currentDetail.SampleVolume = currentDetail.MidValueL * currentDetail.SingleWeight;
                        currentDetail.EverageWeight = currentDetail.SingleWeight * (1 - (groupList.Sum(c => c.CalculateGasWeight * c.OneConcentration)) / 100 / (groupList.Sum(c => c.OneConcentration / 100 * c.CalculateGasWeight) + bottleGas.CalculateGasWeight * (1 - groupList.Sum(c => c.OneConcentration / 100))));
                        DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(currentDetail, c => c.ID == currentDetail.ID, "TotalWeight", "SingleWeight", "BudgetWeight", "SampleVolume", "IsComplete", "MidValueL", "OperOrder", "IsGroupMain", "EverageWeight");
                        foreach (var group in groupList)
                        {
                            if (group.ID != currentDetail.ID)
                            {
                                group.IsComplete = "1";
                                group.OperOrder = currentDetail.OperOrder;
                                //计算质量分数
                                currentDetail.MidValueL = (group.OneConcentration * group.CalculateGasWeight) / 100 / (groupList.Sum(c => c.OneConcentration / 100 * c.CalculateGasWeight) + bottleGas.CalculateGasWeight * (1 - groupList.Sum(c => c.OneConcentration / 100)));
                                group.SampleVolume = currentDetail.SingleWeight * group.MidValueL;
                                DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(group, c => c.ID == group.ID, "SampleVolume", "IsComplete", "TotalWeight", "OperOrder", "MidValueL", "IsGroupMain");
                            }

                        }

                    }
                    else
                    {
                        currentDetail.EverageWeight = detailList.Where(d => d.ID != bottleGas.ID).Sum(d => d.EverageWeight);


                        currentDetail.BudgetWeight = production.MidK3 * currentDetail.BudgetConcentration / 100 * currentDetail.CalculateGasWeight - currentDetail.EverageWeight;
                        var ZFMolWeight = (currentDetail.SingleWeight + currentDetail.EverageWeight) / currentDetail.CalculateGasWeight;

                        DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(currentDetail, c => c.ID == currentDetail.ID, "IsComplete", "SingleWeight", "IsGroupMain", "TotalWeight", "OperOrder");
                    }
                    DALSession.Current.PM_BottleProductionDAL.SaveChanges();
                    if (CompleteNum == detailList.Count - 1)
                    {
                        var saveList = DALSession.Current.PM_BottleProductionDetailDAL.GetListBy(c => c.MainId == production.ID).OrderBy(c => c.IsBottom).ThenBy(c => c.OperOrder).ToList();
                        var saveBottle = saveList.Where(c => c.IsBottom == "1").FirstOrDefault();
                        var ZFMolWeight = (saveBottle.SingleWeight + saveBottle.EverageWeight) / saveBottle.CalculateGasWeight;
                        production.TotalNum = saveList.Where(c => c.IsBottom == "0").Sum(d => d.SampleVolume / d.CalculateGasWeight) + ZFMolWeight;
                        production.State = "1";
                        production.CompletedDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        DALSession.Current.PM_BottleProductionDAL.ModifyBy(production, b => b.ID == production.ID, "TotalNum", "State", "CompletedDate");


                        foreach (var saveDetail in saveList)
                        {
                            if (saveDetail.IsBottom == "0")
                            {
                                saveDetail.Concentration = saveDetail.SampleVolume / saveDetail.CalculateGasWeight / production.TotalNum * 100;
                            }
                            else
                            {

                                saveDetail.Concentration = ZFMolWeight / production.TotalNum * 100;
                            }

                            DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(saveDetail, d => d.ID == saveDetail.ID, "Concentration");

                        }
                    }
                    DALSession.Current.PM_BottleProductionDAL.SaveChanges();
                    Response.Write(JsonHelper.toJson(new { state = "success", msg = "操作完成", TotalNum = production.TotalNum.ToString() }));
                    return;


                    //production.TotalNum = detailList.Sum(d => d.SampleVolume / d.CalculateGasWeight) + ZFMolWeight;



                    //production.State = "1";
                    //production.CompletedDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    //DALSession.Current.PM_BottleProductionDAL.ModifyBy(production, b => b.ID == production.ID, "TotalNum", "State", "CompletedDate");
                    //DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(currentDetail, c => c.ID == currentDetail.ID, "IsComplete", "SingleWeight", "IsGroupMain", "TotalWeight");
                    //DALSession.Current.PM_BottleProductionDetailDAL.SaveChanges();

                    //var saveList = DALSession.Current.PM_BottleProductionDetailDAL.GetListBy(c => c.MainId == production.ID).OrderBy(c => c.IsBottom).ThenBy(c => c.OperOrder).ToList();
                    //var notSaveBottleList = saveList.Where(c => c.IsBottom == "0").ToList();
                    //foreach (var notSaveBottle in notSaveBottleList)
                    //{
                    //    notSaveBottle.Concentration = notSaveBottle.SampleVolume / notSaveBottle.CalculateGasWeight / production.TotalNum * 100;
                    //    DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(notSaveBottle, d => d.ID == notSaveBottle.ID, "Concentration");

                    //}
                    //currentDetail.Concentration = ZFMolWeight / production.TotalNum * 100;
                    //var saveBottle = saveList.Where(c => c.IsBottom == "1").FirstOrDefault();
                    //if (saveBottle != null)
                    //{
                    //    saveBottle.Concentration = 100 - notSaveBottleList.Sum(c => c.Concentration);
                    //    DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(saveBottle, d => d.ID == saveBottle.ID, "Concentration");
                    //}
                    //DALSession.Current.PM_BottleProductionDetailDAL.SaveChanges();
                    //Response.Write(JsonHelper.toJson(new { state = "success", msg = "操作完成", TotalNum = production.TotalNum.ToString() }));
                    //return;
                }
                //else
                //{
                //    var LastDetail = detailList.Where(d => d.IsComplete == "1" && d.IsGroupMain == "1" && d.ID != currentDetail.ID).OrderByDescending(d => d.OperOrder).FirstOrDefault();
                //    if (Commons.String2Decimal(currentDetail.SingleWeight) == 0)
                //    {
                //        currentDetail.SingleWeight = currentDetail.TotalWeight - LastDetail.TotalWeight;
                //    }
                //    else
                //    {
                //        currentDetail.SingleWeight = Commons.String2Decimal(currentDetail.SingleWeight);
                //        currentDetail.TotalWeight = LastDetail.TotalWeight + currentDetail.SingleWeight;
                //    }
                //    currentDetail.IsComplete = "1";
                //    currentDetail.IsGroupMain = "1";
                //    currentDetail.OperOrder = LastDetail.OperOrder + 1;
                //    var groupList = detailList.Where(d => d.InputGroup == currentDetail.InputGroup).ToList();
                //    //计算质量分数
                //    currentDetail.MidValueL = (currentDetail.OneConcentration * currentDetail.CalculateGasWeight) / 100 / (groupList.Sum(c => c.OneConcentration / 100 * c.CalculateGasWeight) + bottleGas.CalculateGasWeight * (1 - groupList.Sum(c => c.OneConcentration / 100)));
                //    currentDetail.SampleVolume = currentDetail.MidValueL * currentDetail.SingleWeight;
                //    currentDetail.EverageWeight = currentDetail.SingleWeight * (1 - (groupList.Sum(c => c.CalculateGasWeight * c.OneConcentration)) / 100 / (groupList.Sum(c => c.OneConcentration / 100 * c.CalculateGasWeight) + bottleGas.CalculateGasWeight * (1 - groupList.Sum(c => c.OneConcentration / 100))));


                //    DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(currentDetail, c => c.ID == currentDetail.ID, "TotalWeight", "SingleWeight", "BudgetWeight", "SampleVolume", "IsComplete", "MidValueL", "OperOrder", "IsGroupMain", "EverageWeight");

                //    foreach (var group in groupList)
                //    {
                //        if (group.ID != currentDetail.ID)
                //        {
                //            group.IsComplete = "1";
                //            group.OperOrder = currentDetail.OperOrder;
                //            //计算质量分数
                //            currentDetail.MidValueL = (group.OneConcentration * group.CalculateGasWeight) / 100 / (groupList.Sum(c => c.OneConcentration / 100 * c.CalculateGasWeight) + bottleGas.CalculateGasWeight * (1 - groupList.Sum(c => c.OneConcentration / 100)));
                //            group.SampleVolume = currentDetail.SingleWeight * group.MidValueL;
                //            DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(group, c => c.ID == group.ID, "SampleVolume", "IsComplete", "TotalWeight", "OperOrder", "", "MidValueL", "IsGroupMain");
                //        }

                //    }
                //    DALSession.Current.PM_BottleProductionDetailDAL.SaveChanges();
                //    int comNum = DALSession.Current.PM_BottleProductionDetailDAL.GetCount(d => d.IsComplete == "1" && d.MainId == production.ID);
                //    if (comNum == detailList.Count - 1)
                //    {
                //        if (bottleGas.OneConcentration != 0 && bottleGas.OneConcentration != null && bottleGas.IsComplete == "0" && currentDetail.IsBottom == "1")
                //        {
                //            bottleGas.EverageWeight = detailList.Where(d => d.ID != bottleGas.ID).Sum(d => d.EverageWeight);


                //            bottleGas.BudgetWeight = production.MidK3 * bottleGas.BudgetConcentration / 100 * bottleGas.CalculateGasWeight - bottleGas.EverageWeight;
                //            //计算底气的相关信息
                //            DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(bottleGas, b => b.ID == bottleGas.ID, "BudgetWeight", "EverageWeight");
                //        }

                //    }
                //    DALSession.Current.PM_BottleProductionDetailDAL.SaveChanges();
                //    Response.Write(JsonHelper.toDefaultMsg(true, "计算完成"));
                //    return;
                //}
            }
        }
        #endregion
    }
}